// Fill out your copyright notice in the Description page of Project Settings.


#include "UserWidget/WidgetComponent/KeyProgressWidget.h"
#include "Components/Border.h"
#include "Components/TextBlock.h"
#include "Kismet/GameplayStatics.h"
#include "Materials/MaterialInstanceDynamic.h"

void UKeyProgressWidget::NativeOnInitialized()
{
	Super::NativeOnInitialized();
	Text = FText::FromString("X");
	TextInColor = FLinearColor(0.745098f, 0.745098f, 0.745098f, 1.f);
	BackgroundInColor = FLinearColor(0.003922f, 0.003922f, 0.003922f, 1.f);
	ProgressInColor = FLinearColor(0.161458f, 0.126903f, 0.06307f, 1.f);
	TargetProgress = 1.f;
	TargetInSeconds = 0.5f;
}

void UKeyProgressWidget::NativeConstruct()
{
	Super::NativeConstruct();
	InteractInTimeMat = InteractInTime->GetDynamicMaterial();
	UpdateInteractionBar(0.f);
	InteractInTime->SetBrushColor(ProgressInColor);
	Background->SetBrushColor(BackgroundInColor);
	KeyText->SetText(Text);
	FSlateColor TempColor(TextInColor);
	KeyText->SetColorAndOpacity(FSlateColor(TextInColor));
}

void UKeyProgressWidget::UpdateProgress(float LTargetProgress, float LInSeconds)
{
	TargetProgress = LTargetProgress;
	TargetInSeconds = LInSeconds;
	FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &UKeyProgressWidget::ProgressTimer);
	GetWorld()->GetTimerManager().SetTimer(ProgressTimerHandle, RespawnDelegate, 0.01, true);
}

void UKeyProgressWidget::UpdateInteractionBar(float Value)
{
	if (InteractInTimeMat->IsValidLowLevel()) {
		InteractInTimeMat->SetScalarParameterValue(FName("Percent"), Value);
	}
}

float UKeyProgressWidget::GetCurrentValue()
{
	float Result = 0.f;
	InteractInTimeMat->GetScalarParameterValue(FHashedMaterialParameterInfo("Percent"), Result);
	return Result;
}

void UKeyProgressWidget::ProgressTimer()
{
	float Temp = FMath::FInterpConstantTo(GetCurrentValue(), TargetProgress, UGameplayStatics::GetWorldDeltaSeconds(this), 1.f / TargetInSeconds);
	UpdateInteractionBar(Temp);
	if (GetCurrentValue() == TargetProgress) {
		GetWorld()->GetTimerManager().ClearTimer(ProgressTimerHandle);
		OnProgressCompleted.Broadcast(GetCurrentValue() == 1.f);
	}
	
}
